<link rel=stylesheet href='./style.css'>
<script src="./vue_3.1.5.js"></script>

<div id=root><div></div></div>

<script>

window.mountApp = element => {
  const app = Vue.createApp({
    template: `
      <app-header :bookCount='books.length'></app-header>
      <new-book @newbook='addNewBook'></new-book>
      <book-list :books='books'></book-list>
      <button-grid></button-grid>
      <div ref="mountPoint"></div>
    `,

    data() {
      return {
        books: [
          {name: 'Pride and Prejudice' },
          {name: 'To Kill a Mockingbird' },
          {name: 'The Great Gatsby' },
        ],
      };
    },

    methods: {
      addNewBook(name) {
        this.books.push({name});
      }
    },
  });

  app.component('app-header', {
    template: `
      <h1>vuejs@${Vue.version}</h1>
      <h3>Reading List: {{ bookCount }}</h3>
    `,
    props: [ 'bookCount' ],
  });

  app.component('new-book', {
    data() {
      return {
        name: '',
      }
    },
    template: `
      <input v-model='name' @keypress.enter='onNewBook'><button @click='onNewBook'>new book</button>
    `,
    emits: ['newbook'],
    methods: {
      onNewBook() {
        this.$emit('newbook', this.name);
      }
    },
  });
  app.component('book-item', {
    template: `
      <div>
        {{ name }}
      </div>
    `,
    props: ['name'],
  });

  app.component('book-list', {
    props: ['books'],
    template: `
      <ol>
        <li v-for='book in books' :key='book.name'>
          <book-item :name='book.name'></book-item>
        </li>
      </ol>
    `,
  });

  app.component('color-button', {
    props: {
      color: String,
      enabled: Boolean,
      nested: {
        index: Number,
        value: Number,
      },
    },
    template: `
      <button :disabled='enabled' :class='color'>button {{nested.index}}</button>
    `,
  });

  app.component('button-grid', {
    render() {
      const buttons = [];
      const ColorButton = Vue.resolveComponent('color-button');
      for (let i = 0; i < 9; ++i) {
        buttons.push(Vue.h(ColorButton, {
          color: ['red', 'green', 'blue'][i % 3],
          enabled: i % 2 === 0,
          nested: {
            index: i,
            value: i + 0.1,
          }
        }, null));
      };
      return buttons;
    }
  });
  return app.mount(element);
}

window.app = window.mountApp(document.querySelector('#root div'));
window.mountNestedApp = () => window.mountApp(window.app.$refs.mountPoint);

</script>
